package com.sunday.haowushop.widgets;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.ZXingUtils;
import com.sunday.common.utils.download.ImgUtils;
import com.sunday.haowushop.R;
import com.sunday.haowushop.common.AppConfig;

import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 刘涛 on 2017/5/19.
 */

public class SaveCodeWindow extends PopupWindow {


    @Bind(R.id.product_title)
    TextView proTitle;
    @Bind(R.id.product_img)
    ImageView proImg;
    @Bind(R.id.product_code)
    ImageView proCode;
    @Bind(R.id.product_price)
    TextView proPrice;
    @Bind(R.id.layout_code)
    LinearLayout layoutCode;

    private View windowView;
    private Context mContext;
    private int appWidth;
    private String shareUrl, productName, productImg, price, productDesc;

    public SaveCodeWindow(Context context, String shareUrl, String productName, String productImg, String price) {
        this.mContext = context;
        windowView = LayoutInflater.from(mContext).inflate(R.layout.activity_save_product_code, null);
        appWidth = DeviceUtils.getDisplay(mContext).widthPixels;
        this.shareUrl = shareUrl;
        this.productName = productName;
        this.productImg = productImg;
        this.price = price;//
        setContentView(windowView);
        ButterKnife.bind(this, windowView);
        this.setWidth(appWidth);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setOutsideTouchable(true);
        this.setFocusable(true);
        this.setOnDismissListener(new SaveCodeWindow.PoponDismissListener());
        this.setBackgroundDrawable(new BitmapDrawable());
        this.setAnimationStyle(R.style.popuwindow);
        initView();
    }
    private void initView() {
        if (!TextUtils.isEmpty(productImg)) {
            Glide.with(mContext)
                    .load(productImg)
                    .error(R.mipmap.ic_default)
                    .into(proImg);
        }
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) proImg.getLayoutParams();
        params.height = DeviceUtils.getDisplay(mContext).widthPixels * 3 / 5;
        proImg.setLayoutParams(params);
        proTitle.setText(productName);
        proPrice.setText("¥"+price);
        Bitmap bitmap = ZXingUtils.createQRImage(shareUrl, 90, 90);
        proCode.setImageBitmap(bitmap);
    }

    @OnClick(R.id.btn_save)
    void save() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(mContext,"没有外部权限", Toast.LENGTH_SHORT).show();
            return;
        }
        new Handler().post(runnable);
    }

    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            viewSaveToImage(layoutCode);
        }
    };

    private void viewSaveToImage(View view) {
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        view.setDrawingCacheBackgroundColor(Color.WHITE);

        // 把一个View转换成图片
        Bitmap cachebmp = loadBitmapFromView(view);

        // 添加水印
        /*Bitmap bitmap = Bitmap.createBitmap(createWatermarkBitmap(cachebmp,
                "@ 好物空投"));*/
        Bitmap bitmap = Bitmap.createBitmap(cachebmp);
        final String filePath = AppConfig.DEFAULT_SAVE_IMAGE_PATH+ ImageUtils.getFileNameForDate();
        try {
            ImgUtils.saveImageToSD(mContext,filePath,bitmap,100);
            ToastUtils.showToast(mContext,"图片保存成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
//        String savePath=ImageUtils.saveBitmap(bitmap);
//        ImgUtils.scanPhoto(mContext,savePath);

        view.destroyDrawingCache();
    }

    private String getFileName(String imgUrl) {
        int index = imgUrl.lastIndexOf('/') + 1;
        if (index == -1) {
            return System.currentTimeMillis() + ".jpeg";
        }
        return imgUrl.substring(index);
    }
    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }
    // 为图片target添加水印
    private Bitmap createWatermarkBitmap(Bitmap target, String str) {
        int w = target.getWidth();
        int h = target.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);

        Paint p = new Paint();

        // 水印的颜色
        p.setColor(Color.RED);

        // 水印的字体大小
        p.setTextSize(16);

        p.setAntiAlias(true);// 去锯齿

        canvas.drawBitmap(target, 0, 0, p);

        // 在中间位置开始添加水印
        canvas.drawText(str, w / 2, h / 2, p);

        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();

        return bmp;
    }

    //显示
    public void showPopupWindow(View parent) {
        if (!this.isShowing()) {
            this.showAtLocation(parent, Gravity.CENTER, 0, 0);
            backgroundAlpha(0.5f);
        } else {
            this.dismiss();
        }
    }



    /**
     * 弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     */
    class PoponDismissListener implements OnDismissListener {

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            backgroundAlpha(1f);
            dismiss();
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = ((Activity) mContext).getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        ((Activity) mContext).getWindow().setAttributes(lp);
    }

}
